'use strict';
const { getDataByText } = require('../utils/utils');

class Zjlx {
  constructor(requestReptile) {
    this.requestReptile = requestReptile;
  }

  // 大盘资金流向
  async zlzjlx() {
    const url = `http://push2.eastmoney.com/api/qt/stock/fflow/kline/get?lmt=0&klt=1&secid=1.000001&secid2=0.399001&fields1=f1,f2,f3,f7&fields2=f51,f52,f53,f54,f55,f56,f57,f58,f59,f60,f61,f62,f63&ut=b2884a393a59ad64002292a3e90d46a5&cb=callback&_=1598966532641`;
    const res = await this.requestReptile(url, 'text');
    const data = getDataByText(res,
      { data: 'data', },
      'data.data.klines',
      'callback'
    );
    const current = data[data.length - 1];
    return current.split(',');
  }

  // 北向资金
  async bxzj() {
    const url = `http://push2.eastmoney.com/api/qt/kamt/get?fields1=f1,f2,f3,f4&fields2=f51,f52,f53,f54,f63&ut=b2884a393a59ad64002292a3e90d46a5&cb=callback&_=1598967862045`;
    const res = await this.requestReptile(url, 'text');
    const data = getDataByText(res,
      { data: 'data', },
      'data.data',
      'callback'
    );

    const arr = ['hk2sh', 'hk2sz'];
    const fieldsMap = {
      // 资金净流入
      dayNetAmtIn: 'zjjlr',
      // 成交净买额
      netBuyAmt: 'cjjme',
      // 当日资金余额
      dayAmtRemain: 'drjjye'
    };
    const bxzj = {
      type: 'bxzj',
      zjjlr: 0,
      cjjme: 0
    };
    const list = arr.map(type => {
      const item = data[type];

      const obj = {
        type: type === 'hk2sh' ? 'hgt' : 'sgt'
      };
      Object.keys(fieldsMap).forEach(key => {
        obj[fieldsMap[key]] = item[key];
      });

      bxzj.zjjlr += obj.zjjlr;
      bxzj.cjjme += obj.cjjme;
      return obj;
    });

    list.push(bxzj);
    return list;
  }
}

module.exports = Zjlx;
